package top.gaui.nurse.controller;

import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.gaui.nurse.entity.Bed;
import top.gaui.nurse.repository.BedRepository;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Fujie_Zeng
 * @version 1.0
 * @date 2020/4/7 20:48
 */
@RestController
@RequestMapping("/bed")
public class BedHandler {
    @Autowired
   private BedRepository bedRepository;

    @GetMapping({"/find/{department}/{page}/{size}",
            "/find/{inpatient}/{department}/{page}/{size}",
            "/find/{inpatient}/{department}/{type}/{page}/{size}",
            "/find/{department}/{type}/{page}/{size}"
            })
    public Page<Bed> find(@PathVariable(required = false)Integer inpatient ,@PathVariable String department,@PathVariable(required = false)String type ,@PathVariable Integer page, @PathVariable Integer size) {
        Specification<Bed> specification = new Specification<Bed>() {
            @SneakyThrows
            @Override
            public Predicate toPredicate(Root<Bed> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (inpatient !=null) {
                    predicateList.add(criteriaBuilder.equal(root.get("inpatient").as(Integer.class),inpatient));
                }
                if(department != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("department").as(String.class),department));
                }
                if(type != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("type").as(String.class),type));
                }



                Predicate[] pre = new Predicate[predicateList.size()];
                criteriaQuery.orderBy(criteriaBuilder.asc(root.get("bed")));
                return criteriaQuery.where(predicateList.toArray(pre)).getRestriction();
            }
        };
        PageRequest request = PageRequest.of(page-1,size);
        return bedRepository.findAll(specification, request);
    }

}
